/**
 * @file     nextLargerNodes.js
 * @brief    [1019. 链表中的下一个更大节点](https://leetcode.cn/problems/next-greater-node-in-linked-list/)
 * @author   Zhu
 * @date     2024-11-28 15:04
 */

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {number[]}
 */
var nextLargerNodes = function (head) {
    const ans = [];

    const stack = [];
    const top = () => stack[stack.length - 1]?.[1];

    let i = 0;
    while (head) {
        ans[i] = 0;
        while (head.val > top()) {
            const [index] = stack.pop();
            ans[index] = head.val;
        }
        stack.push([i, head.val]);
        head = head.next;
        i++;
    }

    return ans;
};
